package com.yhxd.modular.news.service;

import com.yhxd.modular.system.dao.ConfigDao;
import com.yhxd.modular.system.entity.Config;
import com.yhxd.modular.system.service.ConfigService;
import net.bytebuddy.asm.Advice;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class UploadService {

    @Autowired
    private ConfigDao configDao;

    public String uploadFiles(MultipartHttpServletRequest muiltRequest,String path) throws IOException {
        Map<String,Config> map = configDao.findAll().stream().collect(Collectors.toMap(Config::getConfKey, Function.identity()));
        //获取文件格式
        String[] fileFormats=map.get("file_format").getConfValue().split(",");
        //获取文件大小
        int maxSize=Integer.valueOf(map.get("attachment_key").getConfValue());
        String url = map.get("download_upload").getConfValue();
        // 获取遍历文件名
        Iterator iter = muiltRequest.getFileNames();

        while (iter.hasNext()) {
            MultipartFile file = muiltRequest.getFile(iter.next().toString());
            System.out.println("-->>>" + file);
            if (!file.isEmpty() || file != null) {     //获取原始文件名
                String filename = file.getOriginalFilename();
                if (0 != filename.indexOf("\\\\")) {
                    filename = filename.substring(filename.lastIndexOf("\\") + 1);
                }


                InputStream is = file.getInputStream(); // 获取输入流,MultipartFile中可以直接得到文件的流
                int pos = filename.lastIndexOf("."); // 取文件的格式
                //判断文件格式是否满足上传条件
                if(!Arrays.asList(fileFormats).contains(filename.substring(pos+1))){
                    throw new IOException("上传文件格式不正确");
                }
                OutputStream os = new FileOutputStream(path+filename);
                byte[] buffer = new byte[1024*1024*maxSize];
                int len = 0;
                while ((len = is.read(buffer)) > 0) {
                    os.write(buffer, 0, len);
                }
                os.flush();
                os.close();
                is.close();
                url = url+filename + ";";
            }
        }
        url = url.substring(0, url.length() - 1);
        return url;
    }

    private String makeFileName(String filename) {  //2.jpg
        //为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
        return UUID.randomUUID().toString() + "_" + filename;
    }

    /**
     * 为防止一个目录下面出现太多文件，要使用hash算法打散存储
     * @param filename 文件名，要根据文件名生成存储目录
     * @param savePath 文件存储路径
     * @return 新的存储目录
     * @Method: makePath
     */
    private String makePath(String filename, String savePath) {
        //得到文件名的hashCode的值，得到的就是filename这个字符串对象在内存中的地址
        int hashcode = filename.hashCode();
        int dir1 = hashcode & 0xf;  //0--15
        int dir2 = (hashcode & 0xf0) >> 4;  //0-15
        //构造新的保存目录
        String dir = savePath + "\\" + dir1 + "\\" + dir2;
        //File既可以代表文件也可以代表目录
        File file = new File(dir);
        //如果目录不存在
        if (!file.exists()) {
            //创建目录
            file.mkdirs();
        }
        return dir;
    }







}
